package com.changgou.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.goods.feign.SkuFegin;
import com.changgou.goods.pojo.Sku;
import com.changgou.search.SkuInfo;
import com.changgou.search.dao.ESManagerMapper;
import com.changgou.search.service.EsManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class EsManagerServiceImpl implements EsManagerService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ESManagerMapper esManagerMapper;
    @Autowired
    private SkuFegin skuFegin;
    //创建索引库结构
    @Override
    public void createIndexAndMapping() {
        //创建索引
        elasticsearchTemplate.createIndex(SkuInfo.class);
        //创建映射
        elasticsearchTemplate.putMapping(SkuInfo.class);
    }
     //根据spuid查询skulist并存到索引库
    @Override
    public void importDataToESBySpuId(String spuId) {
      //通过fegin的远程调用查询数据库
        List<Sku> skuList = skuFegin.findSkuListBySpuId(spuId);
        //判断查询是否为空,若为空的话则不导入到索引库
        if(skuList == null || skuList.size()<=0){
            //不导入
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        //将数据跟skuinfo相对应
        String skuString = JSON.toJSONString(skuList);
        List<SkuInfo> skuInfoList = JSON.parseArray(skuString, SkuInfo.class);
        for (SkuInfo skuInfo : skuInfoList) {
            //将规格信息进行转换
            Map specMap = JSON.parseObject(skuInfo.getSpec(), Map.class);
            skuInfo.setSpecMap(specMap);
        }
        //添加索引库
        esManagerMapper.saveAll(skuInfoList);
    }

    /**
     * 根据spuid删除索引库sku
     * @param spuId
     */
    @Override
    public void delDataToESBySpuId(String spuId) {
        List<Sku> skuList = skuFegin.findSkuListBySpuId(spuId);
        if (skuList == null || skuList.size()<=0){
            throw new RuntimeException("当前没有数据被查询到,无法导入索引库");
        }
        for (Sku sku : skuList) {
            esManagerMapper.deleteById(Long.parseLong(sku.getId()));
        }
    }
}
